package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.course.ListCourseMessage;
import com.activeshare.edu.ucenter.models.course.CourseDailyRecommendWithCourse;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.newui.task.CourseTask;
import com.xudow.app.ui.adapter.CourseAdapter;
import com.xudow.app.ui.task.CourseListTask;
import com.xudow.app.ui.task.DailyRecommendCoursesTask;
import com.xudow.app.util.Maps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 我的报名Fragment
 *
 * @author lukecheng
 */
public class CourseListFragment extends BaseFragment
        implements CourseAdapter.OnRecyclerViewListener {

    private static final int COURSES_FIRST = 0; //第一次获取
    private static final int COURSES_PREV = 1;  //底部加载更多

    private int refreshStatus = COURSES_FIRST;

    private List<ListCourseMessage.CourseListEntity> courses;
    private CourseAdapter courseAdapter;

    private UltimateRecyclerView orderRecyclerView;

    private LinearLayout contentView;
    private ProgressBar progressBar;
    private RelativeLayout emptyView;

    private CourseListTask courseListTask;

    private int page = 0;  //当前页数

    private String keyword; //搜索关键词
    //筛选条件
    private String level_one; //一级选项
    private String level_two; //二级选项
    private String level_three; //三级选项

    private String areaId; //区域id
    private String agencySchoolId;//大帝区域校区ID
    private int offset=15;//分页条数
   public String gradeids,subjectids;//年级和兴趣编号
    private String searchtype;//查询类别1个人、2机构
    private String sendUserid;//发布者编号
    private String sorttype;//排序类别:1离我最近、2人气最高、3价格最低
    private String timestamp;//最后一次查看时间
    private String course_type;//课程类别 0为艺术 1为文化
    private int sortOption = CourseSearchActivity.SORT_OPTION_DEFAULT; //排序
    CourseTask ct;
    Button bt_listitem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_course_list, container, false);

        emptyView = (RelativeLayout) v.findViewById(R.id.empty_view);
        bt_listitem = (Button) v.findViewById(R.id.bt_listitem);

        progressBar = (ProgressBar) v.findViewById(R.id.progressbar);
        contentView = (LinearLayout) v.findViewById(R.id.content);

        orderRecyclerView = (UltimateRecyclerView) v.findViewById(R.id.order_list);
        orderRecyclerView.setHasFixedSize(false);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        orderRecyclerView.setLayoutManager(layoutManager);

       orderRecyclerView.enableLoadmore();

        //读取本地保存年级"[447,353,354,355,352,351,215,356,357,456,457,458,459]"
        String temp= PreferenceManager.getDefaultSharedPreferences(getMyAct()).getString("GradeIds",
                "");

//        if (!temp.equals(""))
            gradeids=temp.substring(1, temp.length() - 1);
        orderRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
                Handler handler = new Handler();

                if (isgetLastpage) {
                    handler.post(new Runnable() {
                        public void run() {
                            refreshStatus = COURSES_PREV;

                            //设置页数
                            page++;
//                            Log.e("page", page + "");

                            loadMoreCourses(url);

                        }
                    });
                }
            }
        });

        return v;
    }


    //滑动显示隐藏监听
    public void setHildListener(RecyclerView.OnScrollListener listener){
        orderRecyclerView.addOnScrollListener(listener);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        courses = new ArrayList<ListCourseMessage.CourseListEntity>();

        courseAdapter = new CourseAdapter(getActivity(), courses);
        courseAdapter.setOnRecyclerViewListener(this);
        orderRecyclerView.setAdapter(courseAdapter);

        courseAdapter.setCustomLoadMoreView(LayoutInflater.from(getActivity()).inflate(R.layout.item_view_load_more, null));

    }

    @Override
    public void onItemClick(int position) {
        if(courses!=null){
            try {
                Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                intent.putExtra("courseId", courses.get(position).getId());

                startActivity(intent);
            }catch (Exception e){

            }

        }

    }


    @Override
    public boolean onItemLongClick(int position) {
        return false;
    }

    /**
     * 获取课程Handler
     */
    private Handler courseListHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            hideLoadProgress();
            if (msg.what == CourseListTask.SUCCESS) {

                onCourseListSuccess(msg.getData());
            } else {

                if (page > 1) {
                    page--;
                }
                if (page <= 1 && courses.size() <= 0) {
                    contentView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                }

                orderRecyclerView.disableLoadmore();
                courseAdapter.notifyDataSetChanged();

                Toast.makeText(getActivity(), getString(R.string.no_more_data), Toast.LENGTH_SHORT).show();
                return;
//                getApp().makeToast(msg.getData().getString("errMessage"));
            }
        }
    };
    /**
     * 获取课程Handler
     */
    private Handler courseListHandler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            hideLoadProgress();
            if (msg.what == CourseListTask.SUCCESS) {

                onCourseListSuccess(msg.getData());
            } else {

                if (page > 1) {
                    page--;
                }
                if (page <= 1 && courses.size() <= 0) {
                    contentView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                }
                bt_listitem.setVisibility(View.GONE);
                orderRecyclerView.disableLoadmore();
                courseAdapter.notifyDataSetChanged();

                Toast.makeText(getActivity(), getString(R.string.no_more_data), Toast.LENGTH_SHORT).show();
                return;
//                getApp().makeToast(msg.getData().getString("errMessage"));
            }
        }
    };
    private void onCourseListSuccess(Bundle data) {

        ListCourseMessage.CourseListEntity[] courseArr = (ListCourseMessage.CourseListEntity[]) data.getSerializable("courses");

        if (null == courseArr || courseArr.length <= 0) {
//            courses.clear();
            if (page > 1) {
                page--;
            }

            if (page <= 1 && courses.size() <= 0) {
                contentView.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
            }

            orderRecyclerView.disableLoadmore();
            courseAdapter.notifyDataSetChanged();

            Toast.makeText(getActivity(), getString(R.string.no_more_data), Toast.LENGTH_SHORT).show();
            return;
        }

        if (refreshStatus == COURSES_PREV) {
            courses.addAll(Arrays.asList(courseArr));
        } else {
            courses.addAll(Arrays.asList(courseArr));
        }

        if (courses.size()<10){
            orderRecyclerView.disableLoadmore();
        }
        emptyView.setVisibility(View.GONE);
        contentView.setVisibility(View.VISIBLE);
        courseAdapter.notifyDataSetChanged();
    }

    /**
     * 关键词搜索
     */
    public void setKeyword(String keyword) {
        this.page = 1;
        this.keyword = keyword;
    }


    String areaId2;String townId;
    String schoolId;String agencyId;String week;String begindateId;
   String coursePriceId;String semesterid;String enrolling;String coursename;String productId;String at;
    public String ccc;
//    String gradeid;
    /**
     * 第一次加载
     * at  乡镇全部
     * areaId  区ID
     * townId 乡ID
     * schoolId 校区ID
     * agencyId 机构ID
     * week  星期
     * begindateId 时间
     * gradeid 年级
     * coursePriceId 价格
     * semesterid 学期
     * enrolling 班级人数
     */
    public void loadCourses(String ccc,String at,String areaId2,String townId,String schoolId,String agencyId,String week,String begindateId,
                            String gradeid,String coursePriceId,String semesterid,String enrolling,String coursename,String productId) {

        if(ccc!=null){

            if(ccc.equals("不在清理数据")){
                   page=1;
//                this.areaId2=areaId2;
//                this.townId=townId;
//                this.schoolId=schoolId;
//                this.agencyId=agencyId;
//                this.week=week;
//                this.begindateId=begindateId;
//                this.coursePriceId=coursePriceId;
//                this.semesterid=semesterid;
//                this.enrolling=enrolling;
//                this.coursename=coursename;
//                this.at=at;
//                this.page = 1;
//                this.productId=productId;
//                this.ccc=ccc;
            }else if(ccc.equals("不在清理数据2")){

                this.schoolId=schoolId;
                this.agencyId=agencyId;
                this.week=week;
                this.begindateId=begindateId;
                this.coursePriceId=coursePriceId;
                this.semesterid=semesterid;
                this.enrolling=enrolling;
                this.coursename=coursename;
                this.at=at;
                this.page = 1;
                this.productId=productId;
                this.ccc=ccc;
            }else{
                this.areaId2=areaId2;
                this.townId=townId;
                this.schoolId=schoolId;
                this.agencyId=agencyId;
                this.week=week;
                this.begindateId=begindateId;
                this.coursePriceId=coursePriceId;
                this.semesterid=semesterid;
                this.enrolling=enrolling;
                this.coursename=coursename;
                this.at=at;
                this.page = 1;
                this.productId=productId;
                this.ccc=ccc;
            }

        }else{
            this.areaId2=areaId2;
            this.townId=townId;
            this.schoolId=schoolId;
            this.agencyId=agencyId;
            this.week=week;
            this.begindateId=begindateId;
            this.coursePriceId=coursePriceId;
            this.semesterid=semesterid;
            this.enrolling=enrolling;
            this.coursename=coursename;
            this.at=at;
            this.page = 1;
            this.productId=productId;
            this.ccc=ccc;
        }

            HashMap<String, String> params = Maps.newHashMap();
        // params.put(Config.PAGINATION_PARAM_NAME, "" + this.page);

        initSearchParams(params, this.areaId2,this. townId, this.schoolId, this.agencyId, this.week, this.begindateId,
                this.coursePriceId, this.semesterid, this.enrolling, this.coursename);//初始化参数

        emptyView.setVisibility(View.GONE);
        showLoadProgress();

        if (null != this.courses) {
            this.courses.clear();
            this.courseAdapter.notifyDataSetChanged();
        }

        if (null != courseListTask && !courseListTask.isCancelled()) {
            courseListTask.cancel(true);
        }


//        courseListTask = new CourseListTask(getActivity(), courseListHandler);
        ct=new CourseTask(getActivity(),courseListHandler,params);
        ct.CourseList("app/course/list_courseScreen");

//        courseListTask.execute(params);

    }
    String ac;
    public  void  setac(String ac){

         this.ac=ac;
    }
    String asb;
    public  void  setasb(String asb){

        this.asb=asb;
    }
    String ag;
    public  void  setag(String ag){

        this.ag=ag;
    }
    /**
     * 设置搜索参数
     *
     * @param params
     */
    private void initSearchParams(Map<String, String> params,String areaId2,String townId2,String schoolId,String agencyId,String week,String begindateId,
                                  String coursePriceId,String semesterid,String enrolling,String coursename) {

        orderRecyclerView.enableLoadmore();
        params.put("leaveType", this.leaveType);
        params.put("typesTwoname", this.typesTwoname);

        if(at!=null){
                params.put("allTowns", "at");
        }

        if(ac!=null){
         if(ac.equals("ac")){
             params.put("allClasses", "ac");
         }
        }
        if(asb!=null){
            if(asb.equals("asb")){
                params.put("allSubjects ", "asb");
            }

        }
        if(ag!=null){
            if(ag.equals("ag")){
                params.put("allGradeids ", "ag");
            }

        }

//        if(longitude!=0){
            params.put("longitude",String.valueOf(longitude));

//        }

//        if(latitude!=0){
            params.put("latitude",String.valueOf(latitude));

//        }

        params.put("schoolId", schoolId);
        params.put("agencyId", agencyId);

        params.put("begindateId", begindateId);
        params.put("coursePriceId",coursePriceId);
        params.put("semesterid", semesterid);
        params.put("enrolling", enrolling);
        params.put("coursename", coursename);
        Log.i("productId","productId>>>"+productId);
        params.put("productId", productId);
        if(name!=null){
            params.put("gradeids", name);

        }else{

            //三级分类
            if (!TextUtils.isEmpty(level_three)) {
                params.put("level_three", level_three);
            }
        }

            params.put("areaId", areaId2);

            params.put("townId", townId2);
            if(week!=null){
            if(week.equals("星期日")){
                params.put("week", "0");

            }else if(week.equals("星期一")){
                params.put("week", "1");
            }else if(week.equals("星期二")){
                params.put("week", "2");
            }else if(week.equals("星期三")){
                params.put("week", "3");
            }else if(week.equals("星期四")){
                params.put("week", "4");
            }else if(week.equals("星期五")){
                params.put("week", "5");
            }else if(week.equals("星期六")){
                params.put("week", "6");
            }
        }else{
                   params.put("week", null);
         }

        //关键字
        if (!TextUtils.isEmpty(this.keyword)) {
            params.put("coursename", keyword);
        }
        if(ccc!=null){
            params.put("gradeids", gradeids);
        }
        //分页条数
        if (offset!=15) {
            params.put("offset", offset+"");
        }
        //第几页
        if (page!=0) {
            params.put("page", page+"");
        }

        //兴趣
        if (!TextUtils.isEmpty(this.subjectids)) {
            params.put("subjectids", subjectids);
        }
        //查询类别
        if (!TextUtils.isEmpty(this.searchtype)) {
            params.put("searchtype", searchtype);
        }
        //排序类别
        if (!TextUtils.isEmpty(this.sorttype)) {
            params.put("sorttype", sorttype);
        }
        //发布者编号
        if (!TextUtils.isEmpty(this.sendUserid)) {
            params.put("sendUserid", sendUserid);
        }
        //最后一次查看时间
        if (!TextUtils.isEmpty(this.timestamp)) {
            params.put("timestamp", timestamp);
        }
        //一级分类
        if (!TextUtils.isEmpty(level_one)) {
            params.put("level_one", level_one);
        }

        //二级分类
        if (!TextUtils.isEmpty(level_two)) {
            params.put("level_two", level_two);
        }



        //课程类别
        if(!TextUtils.isEmpty(course_type)){
            params.put("course_type",course_type);
        }

        //区域id
        if (!TextUtils.isEmpty(areaId)) {
            params.put("area_id", areaId);
        }

        //按地点最近搜索
        if (CourseSearchActivity.SORT_OPTION_NEARBY == sortOption) {
            XApplication application = (XApplication) getActivity().getApplication();
            params.put("longitude", "" + application.longitude);
            params.put("latitude", "" + application.latitude);
        }

        if (!TextUtils.isEmpty(agencySchoolId)){
            params.put("school_id",agencySchoolId);
        }
    }

    /**
     * 加载更多
     */
    public void loadMoreCourses(String url) {


        HashMap<String, String> params = Maps.newHashMap();
        initSearchParams(params,  this.areaId2, this.townId, this.schoolId, this.agencyId, this.week, this.begindateId,
                this.coursePriceId, this.semesterid, this.enrolling, this.coursename);

        ct=new CourseTask(getActivity(),courseListHandler,params);
        ct.CourseList("app/course/list_courseScreen");

//        if (null==url)
//            courseListTask = new CourseListTask(getActivity(), courseListHandler);
//        else
//            courseListTask = new CourseListTask(getContext(),courseListHandler,url);
//
//        courseListTask.execute(params);
    }

    /**
     * 加载优选课程列表
     */
    private boolean isgetLastpage=true;
    private String url=null;
    public void loadRecommendlist(){

        isgetLastpage=false;
        HashMap<String, String> params = Maps.newHashMap();
        params.put("page",1+"");
        params.put("offset",10+"");
        params.put("gradeids", gradeids);
        url=Config.COURSE_RECOMMED_LIST_URL;
        courseListTask=new CourseListTask(getMyAct(),courseListHandler2,url);
        courseListTask.execute(params);

//        courseListTask=new CourseListTask(getMyAct(),courseListHandler,url);
//        courseListTask.execute(params);
        showLoadProgress();
    }

    /**
     * 加载我发布的课程
     */
    public void LoadMyCourselist(){

        isgetLastpage=false;
        HashMap<String, String> params = Maps.newHashMap();
        params.put("page","1");
        params.put("offset","10");
        url=Config.BASE_URL+Config.MY_SEND_COURSE_URL;
        courseListTask=new CourseListTask(getMyAct(),courseListHandler2,url);
        courseListTask.execute(params);
//        ct=new CourseTask(getActivity(),courseListHandler,params);
//        ct.CourseList(url);

        showLoadProgress();
    }
    /**
     * 隐藏加载进度条
     */
    public void hideLoadProgress() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示加载进度条
     */
    public void showLoadProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        if (null != courseListTask && !courseListTask.isCancelled()) {
            courseListTask.cancel(true);
            courseListTask = null;
        }

        super.onDestroy();
    }

    /**
     * 更新距离
     */
    public void refreshLngLat() {
        courseAdapter.notifyDataSetChanged();
    }
    String leaveType;
    String typesTwoname;

    public void setLevelOneSelected(String levelOneSelected) {
        this.level_one = levelOneSelected;
    }


    public void setleaveType(String leaveType) {
        this.leaveType = leaveType;
    }
    public void settypesTwoname(String typesTwoname) {
        this.typesTwoname = typesTwoname;
    }

    public void setLevelTwoSelected(String levelTwoSelected) {
        this.level_two = levelTwoSelected;
    }
String name;
    public void setname(String name) {
        this.name = name;
    }

    public void setLevelThreeSelected(String levelThreeSelected) {
        this.level_three = levelThreeSelected;
    }

    public void setGradeids(String gradeids) {
        this.gradeids = gradeids;
    }

    public void setSubjectids(String subjectids) {
        this.subjectids = subjectids;
    }

    public void setSearchtype(String searchtype) {
        this.searchtype = searchtype;
    }

    public void setSorttype(String sorttype) {
        this.sorttype = sorttype;
    }

    public void setSendUserid(String sendUserid) {
        this.sendUserid = sendUserid;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public void setAreaId(String areaId) {
        this.areaId = areaId;
    }

    public void setSortOption(int sortOption) {
        this.sortOption = sortOption;
    }
    public void setAgencySchoolId(String id){this.agencySchoolId=id;}
    public void setCourse_type(String t){this.course_type=t;}

    double latitude;
    double longitude;
    public void setlatitude(double latitude){
       this.latitude= latitude;
    }
    public void setlongitude(double longitude){

     this.longitude= longitude;
    }
}